package icu.twtool.ui.router.routes

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import icu.twtool.database.mapper.PracticeRecordMapper
import icu.twtool.database.vo.PracticeExerciseRecordVO
import icu.twtool.ui.component.PagingBar
import icu.twtool.ui.component.PagingState
import icu.twtool.ui.component.rememberPagingState
import icu.twtool.ui.router.Route
import icu.twtool.ui.router.routes.practice.PracticeRecordTable

/**
 * @author Wen
 * @since 2022-11-05
 */
@Composable
@Suppress("FunctionName")
fun PracticeRecordManage() {
    val pagingState = rememberPagingState<PracticeExerciseRecordVO>(1, 1)
    LaunchedEffect(pagingState) {
        refreshState(pagingState)
    }
    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Row(Modifier.padding(16.dp)) {
            Text("要开始新练习，使用习题管理页面", fontStyle = MaterialTheme.typography.caption.fontStyle)
        }
        PracticeRecordTable(pagingState.data)
        Spacer(Modifier.weight(1f))
        PagingBar(
            pagingState,
            modifier = Modifier.align(Alignment.CenterHorizontally)
        ) {
            refreshState(pagingState)
        }
    }
}

private fun refreshState(state: PagingState<PracticeExerciseRecordVO>) {
    state.max = PracticeRecordMapper.count() / state.size + 1
    state.data = PracticeRecordMapper.selectPage((state.page - 1) * state.size, state.size)
}

/**
 * 练习记录管理路由
 */
val practiceRecordManageRoute = Route("练习记录") {
    PracticeRecordManage()
}